package leetcode101.ch5;

//LC 451 根据字符出现频率排序

import javafx.beans.binding.StringBinding;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 桶排序
 */
public class FrequencySort {
    public String frequencySort(String s) {
        Map<Character, Integer> map = new HashMap<>();
        char[] ch = s.toCharArray();
        for (Character c : ch) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }

        List<Character>[] buckets = new List[s.length() + 1];
        for (Character key : map.keySet()) {
            int freq = map.get(key);
            List<Character> bucket = buckets[freq];
            if (bucket == null) {
                bucket = new ArrayList<>();
            }
            bucket.add(key);
            buckets[freq] = bucket;
        }

        StringBuilder tmp = new StringBuilder();
        for (int i = buckets.length -1 ; i > 0 ; i--) {
            List<Character> bucket = buckets[i];
            if (bucket != null) {
                for (Character c : bucket) {
                    for (int j = 0; j < i; j++) {
                        tmp.append(c);
                    }
                }
            }
        }
        return tmp.toString();
    }

    public static void main(String[] args) {
        String s = "Aabb";
        System.out.println(new FrequencySort().frequencySort(s));
    }
}
